try:
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
except ImportError:
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *

from libs.utils import newIcon, labelValidator

BB = QDialogButtonBox


class LabelDialog(QDialog):

    def __init__(self, text="Enter object label", parent=None, listItem=None):
        super(LabelDialog, self).__init__(parent)

        self.listItem = listItem
        self.edit = QLineEdit()
        self.edit.setText(text)
        self.edit.setValidator(labelValidator())
        self.edit.editingFinished.connect(self.postProcess)

        model = QStringListModel()
        model.setStringList(listItem)
        # 增加自动补全
        completer = QCompleter()
        completer = QCompleter()
        # 设置匹配模式  有三种： Qt.MatchStartsWith 开头匹配（默认）  Qt.MatchContains 内容匹配  Qt.MatchEndsWith 结尾匹配
        completer.setFilterMode(Qt.MatchContains)
        # 设置补全模式  有三种： QCompleter.PopupCompletion（默认）  QCompleter.InlineCompletion   QCompleter.UnfilteredPopupCompletion
        # completer.setCompletionMode(QCompleter.PopupCompletion)
        # 给lineedit设置补全器
        completer.setModel(model)
        self.edit.setCompleter(completer)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.edit)
        self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
        bb.button(BB.Ok).setIcon(newIcon('done'))
        bb.button(BB.Cancel).setIcon(newIcon('undo'))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        self.layout.addWidget(bb)

        self.listWidget = QListWidget(self)
        self.setListWidget()
        self.layout.addWidget(self.listWidget)

        self.setLayout(self.layout)

    def setListItem(self, listItem=None):
        self.listItem = listItem
        self.setListWidget()

    def setListWidget(self):
        if self.listItem is not None and len(self.listItem) > 0:
            for item in self.listItem:
                self.listWidget.addItem(item)

            self.listWidget.itemClicked.connect(self.listItemClick)
            self.listWidget.itemDoubleClicked.connect(self.listItemDoubleClick)

    def validate(self):
        try:
            txt = self.edit.text().upper()
            if txt:
                if(txt.find("---") > 0):
                    x = txt.split("---")
                    self.edit.setText(x[0])
                self.accept()
        except AttributeError:
            # PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
            if self.edit.text().strip():
                self.accept()

    def postProcess(self):
        try:
            # 如果是英文字母，则表示这是助记码
            txt = self.edit.text().trimmed().upper()
            txtHz = ""
            if self.is_english_char(txt):
                i = 0
                while(i<self.pingYing.size()):
                    if self.pingYing[i].startswith(txt):
                        txtHz = self.lab

            self.edit.setText(txt)
        except AttributeError:
            # PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
            self.edit.setText(self.edit.text())

    def is_english_char(self, ch):
        if ord(ch) not in (97,122) and ord(ch) not in (65,90):
            return False
        return True

    def popUp(self, text='', move=True):
        self.edit.setText(text)
        self.edit.setSelection(0, len(text))
        self.edit.setFocus(Qt.PopupFocusReason)
        if move:
            self.move(QCursor.pos())
        return self.edit.text() if self.exec_() else None

    def listItemClick(self, tQListWidgetItem):
        try:
            text = tQListWidgetItem.text().trimmed()
        except AttributeError:
            # PyQt5: AttributeError: 'str' object has no attribute 'trimmed'
            text = tQListWidgetItem.text().strip()
        self.edit.setText(text)

    def listItemDoubleClick(self, tQListWidgetItem):
        self.listItemClick(tQListWidgetItem)
        self.validate()
